[CompactString
] is a compact string type that stores itself on the stack if possible,
otherwise known as a "small string optimization".
Memory Layout
Normally strings are stored on the heap, since they're dynamically sized. In Rust a [String
]
consists of three things:
- A
usize
denoting the length of the string - A pointer to a location on the heap where the string is stored
- A
usize
denoting the capacity of the string
On 64-bit architectures this results in 24 bytes being stored on the stack (12 bytes for 32-bit architectures). For small strings, e.g. <= 24 characters, instead of storing a pointer, length, and capacity on the stack, you store the string itself! This avoids the need to heap allocate which reduces the amount of memory used, and improves performance.